import React, { useState,useEffect } from "react";
import './WrjDistribution.less'
import BasicInformation from "../basicInformation/WrjBasicInformation";
import Authentication from "../authentication/WrjAuthentication";
import Authenticated from "../authenticated/WrjAuthenticated";
import { Button, Modal, Input,Select } from 'antd';
import request from "../../../utils/axios";
import { useSelector,useDispatch } from "react-redux";
import {editmobile} from '../../../store/model/counter'


interface Person{
    _id:string,
    name:string,
    frontImg:string,
    backImg:string,
    status:boolean,
    documentType:string,
    idNumber:string
}

const Distribution: React.FC = () => {

    const dispatch=useDispatch()

    //原手机号
    const {mobile,city}=useSelector((store:any)=>store.counter)
    
    const [message,setMessage]=useState('基本信息')
    const [isModalOpenChange, setIsModalOpenChange] = useState(false);
    const [isModalOpenSet, setIsModalOpenSet] = useState(false);
    //输入验证码
    const [codeValue,setCodeValue]=useState('')
    //输入新手机号验证码
    const [newCodeValue,setNewCodeValue]=useState('')

    const [captchaMsg,setCaptchaMsg]=useState('发送验证码')
    const [newCaptchaMsg,setNewCaptchaMsg]=useState('发送验证码')

    const [newMobile,setNewMobile]=useState('')

    //后端获取原手机号验证码
    const [captcha,setCaptcha]=useState('')
    //后端获取新手机号验证码
    const [newCaptcha,setNewCaptcha]=useState('')

    //实名认证
    const authentication=useSelector((store:any)=>store.counter.authentication)


    let time=60
    let newTime=60
    //验证电话号码格式
    function isPhone(tel:string) {
        var regx = /^1[345789]\d{9}$/;
        return regx.test(tel);
    }

    //加密号码
    function maskPhoneNumber(phoneNumber:string | null) {
        // 确保手机号是有效的
        if (!phoneNumber || phoneNumber.length !== 11) {
          return 'Invalid phone number';
        }
        // 使用正则表达式匹配中间四位数字
        const maskedPhone = phoneNumber.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
        return maskedPhone;
    }

    const options = [
        {
            value: '+86中国大陆',
            label: '+86中国大陆',
        },
        {
            value: '+852中国香港',
            label: '+852中国香港',
        },
        {
            value: '+853中国澳门',
            label: '+853中国澳门',
        },
        {
            value: '+886中国台湾',
            label: '+886中国台湾',
        },
    ];

    //原手机号验证码
    const sendCroeCode=async()=>{
        let times=setInterval(()=>{
            time-=1
            setCaptchaMsg(`${time}秒后重发`)
            if(time==0){
                clearInterval(times)
                setCaptchaMsg('发送验证码')
            }
        },1000)
        request.post('sendCroeCode', { mobile:mobile })
        .then(error => {
            console.log('POST error:', error);
        })
        .catch(response => {
            setCaptcha(response.data.captcha)
        });
    }

    // 下一步
    const nextCode=async()=>{
        if(codeValue==''){
            alert('请输入验证码')
        }else{
            request.post('nextCode', { mobile:mobile,captcha:codeValue })
            .then(error => {
                console.log('POST error:', error);
            })
            .catch(response => {
                setCaptcha(response.data.captcha)
                if(response.datacode!=200){
                    alert(response.data.msg)
                }else{
                    setIsModalOpenChange(false)
                    setIsModalOpenSet(true)
                }
            });
        }
    }

    //新手机号
    const sendNewCroeCode=async()=>{
        if(newMobile==""){
            alert("请输入手机号")
        }else{
            if(!isPhone(newMobile)){
                alert("手机号格式错误")
            }else{
                let newTimes=setInterval(()=>{
                    newTime-=1
                    setNewCaptchaMsg(`${newTime}秒后重发`)
                    if(newTime==0){
                        clearInterval(newTimes)
                        setNewCaptchaMsg('发送验证码')
                    }
                },1000)
                request.post('sendCroeCode', { mobile:newMobile })
                .then(error => {
                    console.log('POST error:', error);
                })
                .catch(response => {
                    setNewCaptcha(response.data.captcha)
                });
            }
        }
    }

    // 更换新绑定手机号
    const editMobile=async()=>{
        request.post('nextCode', { mobile:newMobile,captcha:newCodeValue })
        .then(error => {
            console.log('POST error:', error);
        })
        .catch(response => {
            setNewCaptcha(response.data.captcha)
            if(response.data.code!=200){
                alert(response.data.msg)
            }else{
                request.put('editMobile', { phone:mobile, mobile:newMobile})
                .then(error => {
                    console.log('PUT update subaccount error:', error);
                })
                .catch(response => {
                    setIsModalOpenSet(false)
                    dispatch(editmobile(newMobile))
                    
                });
            }
        })
    }

    // 实名认证
    const [IdName,setIdName]=useState('')

    const getpeople=async()=>{
        if(authentication!=''){
            request.get('getPeople',{ _id:authentication})
            .then(error => {
                console.log('GET getPeople success:', error.data);
            }).catch(response => {
                setIdName(response.data.peopleList[0].name)            
            })
        }
    }


    const [ridersPositions,setRidersPositions]=useState([]);
    //获取配送员信息
    const getManage=async()=>{
        request.get('manage').then(response=>{
            setRidersPositions(response)
        }).catch(error=>{
            return error
        })
    }
    
    useEffect(()=>{
        getpeople() 
        getManage()     
    },[])

    return (
        <div style={{marginLeft:'15px',marginTop:'10px'}}>
            <p className="wrj-distribution-p">关于配送站</p>
            <div className="wrj-distribution-top">
                <div className="wrj-left">
                    <svg className="wrj-icon" viewBox="0 0 1088 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="23477" width="28" height="28"><path d="M788.608 550.4c20.48 56.192 70.4 96 128.704 96 10.304 0 20.352-1.28 30.016-3.712L956.8 640v318.208c0 27.52-25.216 60.672-49.92 65.28l-5.632 0.512H165.44c-24.448 0-51.456-31.168-55.168-59.328l-0.448-6.4V639.808c12.8 4.288 26.112 6.528 39.488 6.528 58.304 0 108.288-39.808 128.64-96 20.224 56.192 69.76 96 127.36 96 58.304 0 108.288-39.808 128.704-96 20.16 56.192 69.632 96 127.36 96 57.6 0 107.072-39.808 127.232-96z m166.016-407.936l90.688 258.24c0 78.912-58.496 141.44-128.704 141.44-71.68 0-128.768-64.192-128.768-141.44 0 78.912-57.024 141.44-127.232 141.44S533.312 477.888 533.312 400.64c0 78.912-58.496 141.44-128.704 141.44S277.312 477.888 277.312 400.64c0 78.912-58.496 141.44-128.704 141.44-67.2 0-122.24-58.688-126.976-131.456L21.312 400.64l87.808-258.24h845.504zM893.568 0a49.28 49.28 0 0 1 0 98.688H173.056a49.28 49.28 0 1 1 0-98.688h720.512z" fill="#ffffff" p-id="23478"></path></svg>
                </div>
                <div className="wrj-center">
                    <div>
                        <p>
                            <span style={{color:'gray'}}>站点信息：</span>
                            <span>{city}</span>
                        </p>
                        <p>
                            <span style={{color:'gray'}}>所在地：</span>
                            <span>{city}</span>
                        </p>
                    </div>
                    <div>
                        <p>
                            <span style={{color:'gray'}}>站长姓名：</span>
                            {
                                authentication==''?
                                <span>未认证</span>:
                                <span>{IdName}</span>
                            }
                        </p>
                        <p>
                            <span style={{color:'gray'}}>手机号码：</span>
                            <span>+86{maskPhoneNumber(mobile)}</span>
                        </p>
                    </div>
                    <div>
                        <p>
                            <span style={{color:'gray'}}>配送员：</span>
                            <span>{ridersPositions.length}人</span>
                        </p>
                        <p>
                            <span style={{color:'gray'}}>状态：</span>
                            <span>正常</span>
                        </p>
                    </div>
                </div>
                <div className="wrj-right">
                    <button onClick={()=>{setIsModalOpenChange(true)}}>更换手机号</button>
                </div>
            </div>
            <div className="wrj-distribution-message">
                <span className={message=='基本信息'?'wrj-message-active':'wrj-message-span'} onClick={()=>{setMessage('基本信息')}}>基本信息</span>
                <span className={message=='实名认证'?'wrj-message-active':'wrj-message-span'} onClick={()=>{setMessage('实名认证')}} style={{marginLeft:'30px'}}>
                    实名认证
                </span>
                {
                    authentication==''?
                    <span className="wrj-no-authentication">未认证</span>:
                    <span></span>
                }
            </div>
            <div style={{marginTop:'30px'}}>
                {
                    message=='基本信息'?
                    <BasicInformation></BasicInformation>:
                    authentication==''?
                    <Authentication></Authentication>:
                    <Authenticated></Authenticated>
                }
            </div>
            <Modal title="更换手机号" open={isModalOpenChange} onOk={nextCode} onCancel={()=>{setIsModalOpenChange(false)}} cancelText='取消' okText='下一步'>
                <p style={{marginBottom:'10px'}}>请输入 +86{maskPhoneNumber(mobile)} 收到的短信验证码，以完成身份验证。</p>
                <Input placeholder="请输入短信验证码" style={{ width: 200 }} onChange={(e:React.ChangeEvent<HTMLInputElement>)=>{setCodeValue(e.target.value)}}/>
                <Button onClick={sendCroeCode}>{captchaMsg}</Button>
            </Modal>
            <Modal title="设置手机号" open={isModalOpenSet} onOk={editMobile} onCancel={()=>{setIsModalOpenSet(false)}} cancelText='取消' okText='确定'>
                <p style={{marginBottom:'10px'}}>
                    新手机号：<Select defaultValue="+86中国大陆" options={options} />
                    <Input placeholder="请输入新手机号" onChange={(e:React.ChangeEvent<HTMLInputElement>)=>{setNewMobile(e.target.value)}} style={{ width: 200,marginLeft:'10px' }} />
                </p>
                <p>
                    短信验证码：<Input placeholder="请输入短信验证码" onChange={(e:React.ChangeEvent<HTMLInputElement>)=>{setNewCodeValue(e.target.value)}} style={{ width: 200 }} />
                    <Button onClick={sendNewCroeCode}>{newCaptchaMsg}</Button>
                </p>
            </Modal>
        </div>
    );
};

export default Distribution;